<template>
	<view class="container">
        <!-- 公共组件-每个页面必须引入 -->
        <public-module></public-module>
		<!--banner-->
		<view class="tui-banner-swiper">
			<view v-if="goods.images.length==0">
				
          <u--image
            :showLoading="true"
            :src="goods.cover_url"
            :lazy-load="true"
            :fade="true"
            duration="450"
            width="100%"
			v-if="goods.cover_url!=''">
			<template v-slot:loading><u-loading-icon ></u-loading-icon></template>
          </u--image>
				
			</view>
			<view v-else>
			<u-swiper :list="goods.images" keyName="file_original" imgMode="aspectFill" :height="picheight" :radius="0" circular radius="0"></u-swiper>
			</view>
		</view>
		<!--banner-->

		<!--商品简介-->
		<view class="tui-pro-detail" v-if="loadstatus==false">
			<view class="tui-product-title tui-border-radius">
				<!-- 邀新拼团 -->
				<view class="yxpt" >
					<view class="yxpt_l" style="width: 100%;">
						<view class="yxpt_l_l">线上<br />专享</view>
						<view class="yxpt_l_r">
							<span>{{siteInfo.money.symbol}} {{goods.price}}</span>
							<span style="font-size: 12px;"></br>{{$t('promise48hours')}}</span>
						</view>
					</view>
					<view class="yxpt_r">包退运费<br/>售后无忧</view>
				</view>

				<!-- 限时折扣 ↓↓	-->
				<!--block >
					<view class="detail">
						<view>
							<view class="tui-pro-pricebox tui-padding red">
								<view class="tui-pro-price">
									<view>￥<text class="tui-price">fdsa</text></view>
									<view class="tag">新品</view>
								</view>
							</view>
							<view class="tui-original-price tui-gray">
								价格
								<text class="tui-line-through">￥fdasf</text>
							</view>
						</view>
						<view class="time">
							<view class="juli">距离活动结f束还剩</view>afd
						</view>
					</view>
				</block-->


				<!-- 享超值优惠价 -->
				<!--block class="">
					<view class="kait">
						<view class="kt_01">
							<img src="@/static/imgs/vip.png"></img>
						</view>
						<view class="kt_02">VIP享超值优惠价</view>
						<view class="kt_03" >立即开通</view>
					</view>
				</block-->


				<view class="tui-pro-titbox">
					<view class="tui-pro-title">
						{{goods.name}}
					</view>
					<button @click="is_share=true" class="tui-share-btn tui-share-position share" style="margin-top: -7px;">
						<h-tag type="gray" tui-tag-class="tui-tag-share tui-size" shape="circleLeft" size="small">
							<i class="iconfont iconfont-share u-font-12"></i>
							<text class="tui-share-text tui-gray">{{$t('share')}}</text>
						</h-tag>
					</button>
				</view>
				<view class="b-b"></view>
					<block v-if="goods.title!=''">
						<view class="tui-sub-title tui-size font-red u-p-l-30">{{goods.title}}</view>
						<view class="b-b"></view>
					</block>
				<view class="tui-padding" >
					<view class="tui-sale-info tui-size tui-gray">
						<view>{{$t('stock')}}：{{goods.stock_num}}</view>
						<view><span v-if="goods.sales_totalnum!=''">{{goods.sales_totalnum}}{{$t('x_personpaid')}}</span></view>
						<view v-if="goods.brand_info.name!=''">
						<i class="iconfont iconfont-f4"></i>{{goods.brand_info.name}}</view>
					</view>
				</view>
			</view>

			<!--view class="tui-discount-box tui-radius-all tui-mtop" >
				<view class="tui-list-cell"  @click="toggleMask('show')">
					<view class="tui-bold tui-cell-title">领券</view>
					<view class="tui-tag-coupon-box">
							<h-tag size="small" type="red" shape="circle" tui-tag-class="tui-tag-coupon">满3减1</h-tag>
					</view>
					<i class="iconfont icon-arrow-right-bold"></i>
				</view>
			</view-->



			<!-- *****************  拼团  start ***************** -->
			<!--view class="pintuan tui-radius-all tui-mtop" >
				<view class="pt_top">
					<view class="pt_top_l">1人在拼单，可直接参与</view>
					<view class="pt_top_r">查看更多
					</view>
				</view>
				<view class="pt_people">
					<view class="pt">
						<block >
							<view class="pt_l">
								<img src="@/static/imgs/vip.png"></img>
								<view>jjk</view>
							</view>
							<view class="pt_m">
								<view>还差<span>2人</span>拼成</view>
								<view class="pt_m_2">剩余
									1
								</view>
							</view>
							<view class="pt_r" >去拼单</view>
						</block>

					</view>
				</view>
			</view>
			<view class="haoyou tui-radius-all tui-mtop" >
				<view class="hy_l">玩法</view>
				<view class="hy_m">开团后邀请好友参团，人满发货（不满退款）</view>
				<view class="hy_r"><i class="iconfont icon-arrow-right-bold"></i></view>
			</view-->
			<!-- *****************  拼团 end ***************** -->


			<view class="pro-content"> 
				<view class="h-nomore-box u-padding-4">
					<u-divider :text="$t('details')" :hairline="true" textColor="#e5e5e5"></u-divider>
				</view>
				<view class="tui-product-img tui-radius-all">
					<u-parse :content="goods.content"></u-parse>
				</view>
			</view>

			
			
			
			<view class="tui-cmt-box tui-mtop tui-radius-all">
				<!--view class="tui-list-cell tui-last tui-between">
					<view class="tui-bold tui-cell-title" style="width: 100px;">评价</view>
					<view >
						<text class="tui-cmt-all">查看全部</text>
					</view>
				</view-->

				<ygcComment
					ref="ygcComment"
					:placeholder="'高楼平地起，评论全靠您~'"
					labelPosition="bottom"
					:commenttitle="'已购评论'"
					:root_id="goods.goods_id"
					:showmode="'onlylist'"
					:module="'shop_goods'"
				></ygcComment>

				<!--view class="tui-cmt-btn">
					<h-tag type="black" :plain="true" tui-tag-class="tui-tag-cmt">查看全部评价</h-tag>
				</view-->
			</view>
			
			<view class="u-padding-20"><u-divider :text="$t('atbottom')" :hairline="true" textColor="#cccccc"></u-divider></view>

			<view class="tui-safearea-bottom"></view>

		</view>

		<!--底部操作栏-->
		<view class="tui-operation">
			<view class="tui-operation-left tui-col-5 ">
				<view class="tui-operation-item pad" hover-class="opcity" :hover-stay-time="150" @tap="$tools.goJump('/pages/index/index',{},'','tab')">
					<u-icon name="jingxuanchanpinku" custom-prefix="iconfont" size="20"></u-icon>
					<view class="tui-operation-text tui-scale-small">{{$t('pagetitle.index')}}</view>
				</view>
				<view class="tui-operation-item" hover-class="opcity" :hover-stay-time="150" @tap="$tools.goJump('/pages/goods/cart',{},'','')">
					<u-icon name="cart" custom-prefix="iconfont" size="20"></u-icon>
					<view class="tui-operation-text tui-scale-small">{{$t('cart')}}</view>
					<u-badge type="warning" max="99" :value="carnum" :absolute="true" :offset="[-1,-6]">1</u-badge>
				</view>
				<view class="tui-operation-item pad"    hover-class="opcity" :hover-stay-time="150" @tap="addToFavorites">
					<u-icon :name="isFavorites ? 'shoucangxuanzhong' : 'shoucang'" custom-prefix="iconfont" size="20"></u-icon>
					<view class="tui-operation-text tui-scale-small" :style="''">{{$t('collect')}}</view>
				</view>
				<view style="width: 5px;"></view>
			</view>
			<view class="tui-operation-right tui-right-flex tui-col-7 tui-btnbox-4">
				<view class="tui-flex-1" >
					<h-button type="danger" shape="circle" size="mini" @click="onDetermine(goods)">{{$t('addtocart')}}</h-button>
				</view>
				<view class="tui-flex-1" >
					<h-button type="warning" shape="circle" size="mini" @click="onPurchase(goods)">{{$t('buynow')}}</h-button>
				</view>
			</view>
		</view>
		<!--底部操作栏--->

		<!-- 优惠券面板 -->
		<view class="mask" :class="maskState===0 ? 'none' : maskState===1 ? 'show' : ''" @click="toggleMask">
			<view class="mask-content">
				<!-- 优惠券页面，仿mt -->
				<view class="coupon-item">
					<view class="con">
						<view class="left">
							<text class="title">aaaaa</text>
							<text class="time">有效期至2222</text>
						</view>
						<view class="right">
							<text class="price">22</text>
							<text>满100可用</text>
						</view>

						<view class="circle l"></view>
						<view class="circle r"></view>
					</view>
					<view class="dott">
						<text class="tips">限新用户使用</text>
						<div class="an" @click="lq_coupon(item.id)">立即领取</div>
					</view>

				</view>
			</view>

		</view>

		<!-- 分享 -->
		<view class="sha_tan" v-if="is_share">
			<view class="mask" @click="is_share=false"></view>
			<view class="share_tan">
				<view class="s_title">— · {{$t('share')}} · —</view>
				<view class='u-p-b-40'>
					<view class='s_t_x'>
						<view class='s_t_l'>
							<button open-type="share" @click="clipboardcopy" class="s_t_l_s share"><img src='@/static/imgs/share1.png' /></button>
						</view>
						<view class='s_t_l'>
							<view class='s_t_l_s' @click="shareFc"><img src='@/static/imgs/share2.png' /></view>
						</view>
					</view>
					<view class='s_t_x'>
						<view class='s_t_l'>
							<button open-type="share" class="share">{{$t('tofriends')}}</button>
						</view>
						<view class='s_t_l'>
							<view bindtap='show_hb'>{{$t('poster')}}</view>
						</view>
					</view>
				</view>
				<view class="bye" @click="is_share=false">{{$t('cancel')}}</view>
			</view>
		</view>
		<hPoster ref="hchPoster" :canvasFlag.sync="canvasFlag" @cancel="canvasCancel" :posterObj.sync="posterData" />
		<view :hidden="canvasFlag">
			<!-- 海报 要放外面放组件里面 会找不到 canvas-->
			<canvas class="f__canvas" canvas-id="firstCanvas" id="firstCanvas" style="width:600px;height:730px"></canvas>
        <!-- 二维码 -->
        <canvas class="f__canvas" canvas-id="qrcode" id="qrcode" width="300" height="300" style="width:300px;height:300px;"></canvas>
		</view>
        <!-- 规格弹窗 -->
        <u-popup :show="isPopup" :round="10" mode="bottom" @close="isPopup = false">
            <specs-popup :goodsinfo="goods" :cart="cart" :isPopup="isPopup" :popupType="popupType" @change="onSpecChange"></specs-popup>
        </u-popup>
	</view>
</template>

<script>
	import { mapState, mapMutations } from 'vuex';
	import base from '@/config/baseUrl.js';
	import hTag from "@/components/module/h-tag/tag"
	import hButton from "@/components/module/h-button/button"
	import hPoster from '@/components/module/h-poster/h-poster.vue'
	import specsPopup from './module/specs-popup';
	import { api_goods_item } from '@/config/api.js';
	import ygcComment from "@/components/ygc-comment/ygc-comment.vue";
	export default {
		components: {
			hTag,hButton,specsPopup,hPoster,ygcComment
		},
		data() {
			return { 
				goods_id:'',
				picheight:(base.systemInfo.windowWidth/1.68)+'px',
				goods:{
					images:[],
					brand_info:{
						name:''
					}
				},
				loadstatus:true,
				is_share:false,//分享面板
				maskState:0,//优惠券面板显示状态
				cart: [], //购物车
				carnum:0,
				isPopup:false,
				popupType:1,
				canvasFlag: true,
				posterData: {},
				qrcodeImg:'',    //二维码本地图片
				isFavorites:false,//是否收藏
				site_info:{
					money:{
						symbol:''
					}
				}
			}
		},
		onReady() {
		},
		onLoad: function(options) {
			
			this.cart =uni.getStorageSync('cartStorage')||JSON.parse('[]');
			this.goods_id = options.id
			if(options.sfm){
				uni.setStorageSync('level_one',options.sfm)	//上级分销的身份码
				//A分销商品给B，B直接进入商品页，无任何操作又分享给C，此时B的分享不属于分销
				//B浏览其他页面后再分享C，此时才属于分销
			}
			this.getGoodsInfo()
			this._load()		
			uni.setNavigationBarTitle({title: this.$t('pagetitle.goodsview')});
			//uni.setStorageSync('goodsFavorite', '');
			//uni.setStorageSync('goodsFavorite-' + this.goods.goods_id, '');
		},
	computed:{
	    ...mapState(['userInfo','siteInfo']),
	},
    watch: {
		cart:{
			handler(tnew,old){
				this.carnum=tnew.reduce((acc, cur) => {
					return acc += cur.num
				}, 0)
			},
			immediate:true
		},
    },
	
		methods: {
			_load() {
			},
		handle_Cart(data){
			this.cart=data
			uni.setStorageSync('cartStorage', this.cart)
		},
        //规格回调
        onSpecChange(e){
			this.handle_Cart(e.cart)
            if(e.type!=1 && e.type!=4 ){
                this.isPopup = false
            }
        },
			// 加入购物车
            onDetermine(e) {
                this.popupType=1
				this.isPopup=true
            },
            //去购买
            onPurchase(e){
                this.popupType=3
				this.isPopup=true
            },
			//获取商品
            getGoodsInfo(){
				api_goods_item({
					goods_id:this.goods_id
				},{custom: {load:true}}
				).then((res) => {
					console.log("aaa",res)
					this.loadstatus=false
					this.goods=res
					console.log(res)
					if (res.sku_arr.list.length>0){
						res.sku_arr.initialSku = {}
						res.sku_arr.initialSku['selectedNum'] = 1
						res.category_id=0
						for (let [k, v] of Object.entries(res.sku_arr.tree)) {
							res.sku_arr.initialSku[v.k_s] = ''
						}
					}
					uni.getStorage({
						key: 'goodsFavorite',
						success: rs1 => {
							if (rs1.data && rs1.data.indexOf(parseInt(this.goods_id)) > -1) {
								this.isFavorites = true;
							}
						},
						fail: function(err) {
							console.log(err);
						}
					});
				}).catch((err) =>{})
            },
			lq_coupon(id) { //领取优惠券

			},
			//显示优惠券面板
			toggleMask(type) {
				let timer = type === 'show' ? 10 : 300;
				let state = type === 'show' ? 1 : 0;
				this.maskState = 2;
				setTimeout(() => {
					this.maskState = state;
				}, timer)
			},
			//复制
			clipboardcopy(){
				let salt
				if (this.userInfo.token){
					salt=this.userInfo.salt
				}else{
					salt="&loginnull=Login to receive a sharing code and surprise rewards"
				}
				let href=this.siteInfo.site.webname+' '+this.siteInfo.site.desc+' '+this.siteInfo.site.domain+'/h5/#/pages/goods/view?id='+this.goods.goods_id+'&sfm='+salt
				let that = this;
				uni.setClipboardData({
					data: href,
					success: function (data) {
					  that.$u.toast(that.$t('linkcopid'));
					},
					fail: function (err) {},
					complete: function (res) {},
				});
			},
			//海报开关
			canvasCancel(val) {
				this.canvasFlag = val;
			},
			//生成海报
			shareFc() {
				let avatar_url
				let nickname
				let salt
				if (this.userInfo.token){
					avatar_url=this.userInfo.token
					nickname=this.userInfo.usernick
					salt=this.userInfo.salt
				}else{
					avatar_url=this.siteInfo.site.logo
					nickname=this.siteInfo.site.webname
					salt=""
				}
				// 这个是固定写死的小程序码
				Object.assign(this.posterData, {
					url: this.goods.cover_url, //商品主图
					title: this.goods.name, //标题
					goodsdescription:this.goods.description,
					discountPrice: this.goods.price, //折后价格
					orignPrice: this.goods.price_market, //原价
					// code: 'https://img0.zuipin.cn/mp_zuipin/poster/hch-code.png', //小程序码
					qrcodetxt: this.siteInfo.site.domain+'/h5/#/pages/goods/view?id='+this.goods.goods_id+'&sfm='+salt,    //二维码本地图片, //小程序码
					webdesc:this.siteInfo.site.desc,
					priceymbol:this.siteInfo.money.symbol,
					avatar_url:avatar_url,
					nickname:nickname
					
				})
				this.$forceUpdate(); //强制渲染数据
				console.log('生成海报',this.posterData)
				setTimeout(() => {
					this.canvasFlag = false; //显示canvas海报
					this.is_share = false; //关闭分享弹窗
					//this.$refs.hchPoster.createQrcode();
					this.$refs.hchPoster.createGoodsPoster(); //调用子组件的方法
					
				}, 1500)
			},
			addToFavorites: function() {
				
				let self = this;
				self.isFavorites = !self.isFavorites;
				let hasid = uni.getStorageSync('goodsFavorite');
				if (!hasid && !self.isFavorites) {
					// 当前是删除，直接返回
					return;
				}

				let pos = hasid.indexOf(parseInt(self.goods_id));
				if (!self.isFavorites) {
					// 当前删除
					if (pos > -1 ) {
						hasid.splice(pos, 1);
						uni.removeStorageSync('goodsFavorite-' + self.goods_id);
					}
				} else {
					// 增加
					if (pos === -1) {
						hasid=hasid?hasid:[];
						hasid.push(parseInt(self.goods_id));
					}
					let theinfo={
						goods_id:self.goods_id,
						name:self.goods.name,
						cover:self.goods.cover_url
					}
					uni.setStorageSync('goodsFavorite-' + self.goods_id, theinfo);
				}
				uni.setStorageSync('goodsFavorite', hasid);	
			}

		},
		
		
		
		onPageScroll(e) {
			let scroll = e.scrollTop <= 0 ? 0 : e.scrollTop;
			let opcity = scroll / this.scrollH;
			if (this.opcity >= 1 && opcity >= 1) {
				return;
			}
			this.opcity = opcity;
			this.iconOpcity = 0.5 * (1 - opcity < 0 ? 0 : 1 - opcity)
		},
		
		//小程序右上角原生菜单分享按钮，也可是页面中放置的分享按钮
		onShareAppMessage(res) { 
			let my = uni.getStorageSync('my')
			let path="/pages/goods/view?id="+this.goods_id
			if(this.userInfo.token&&this.userInfo.is_sunline==1){
				 path = path + '&sfm='+this.userInfo.salt
			}	
			console.log('path:',path)
			return {
			  title: this.goods.name,
			  path: path
			}
		},
		
		onPullDownRefresh() {
			//this._load()
			setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 2000);
		},

	}
</script>

<style lang="scss">


	page {
		background: #f5f5f5;
	}
	@import '~@/pages/goods/module/shop.scss';

</style>
